<?php
/**
 * This is Area model file. 
 *
 * @copyright     Copyright 2008-2010, LilCake.net
 * @link          http://lilcake.net LilCake.net
 * @package       lil
 * @subpackage    lil.models
 * @license       MIT License (http://www.opensource.org/licenses/mit-license.php)
 */
/**
 * Area class
 *
 * @uses          LilAppModel
 * @package       lil
 * @subpackage    lil.models
 */
class Area extends LilAppModel {
/**
 * name property
 *
 * @var string 'Area'
 * @access public
 */
	var $name = 'Area';
/**
 * actsAs property
 *
 * @var array
 * @access public
 */
	var $actsAs = array('Containable');
/**
 * recursive property
 *
 * @var int
 * @access public
 */
	var $recursive = -1;
/**
 * validate property
 *
 * @var array
 * @access public
 */
	var $validate = array(
		'name' => array(
			'rule' => array('minLength', '1'),
			'required' => true
		),
		'slug' => array(
			'rule' => 'checkShortName',
			'required' => false,
			'allowEmpty' => true
		),
	);
/**
 * __construct method
 *
 * @param mixed $id
 * @param mixed $table
 * @param mixed $ds
 * @access private
 * @return void
 */
	function __construct($id = false, $table = null, $ds = null) {
		if ($areas = Configure::read('Lil.noAreas')) {
			$this->useTable = false;
		} else {
			$this->useTable = Configure::read('Lil.areasTable');
			
			$this->hasAndBelongsToMany['User'] = Configure::read('Lil.userAssociation');
			$this->hasAndBelongsToMany['User']['joinTable'] = Configure::read('Lil.areasUsersTable');
			
			$assoc_key = $this->hasAndBelongsToMany['User']['associationForeignKey'];
			$this->hasAndBelongsToMany['User']['associationForeignKey'] = $this->hasAndBelongsToMany['User']['foreignKey'];
			$this->hasAndBelongsToMany['User']['foreignKey'] = $assoc_key;
			
			$this->hasAndBelongsToMany['User']['with'] = 'Lil.AreasUser';
		}
		
		if (Configure::read('Lil.areaSlugField') != 'slug') {
			$this->validate[Configure::read('Lil.areaSlugField')] = $this->validate['slug'];
			unset($this->validate['slug']);
		}
		parent::__construct($id, $table, $ds);
	}
/**
 * checkShortName method
 *
 * @param array $data
 * @access public
 * @return boolean
 */
	function checkShortName($data) {
		if (Configure::read('Lil.slug') == 'auto') {
			return true;
		} else {
			return preg_match('/^[a-zA-Z0-9_-]+$/', $data[Configure::read('Lil.areaSlugField')]);
		}
	}
/**
 * beforeSave callback
 *
 * @access public
 * @return boolean
 */
	function beforeSave() {
		$slug_field = Configure::read('Lil.areaSlugField');
		if (empty($this->data[$this->alias][$slug_field]) && !empty($this->data[$this->alias]['name'])) {
			$this->data[$this->alias][$slug_field] = strtolower(Inflector::slug($this->data[$this->alias]['name'], '-'));
			
			$conditions = array(
				$this->alias . '.' . $slug_field => $this->data['Area'][$slug_field],
			);
			if (!empty($this->data['Area']['id'])) {
				$conditions['NOT'] = array('Area.id' => $this->data['Area']['id']);
			}
			
			// find non-existant slug
			if ($this->hasAny($conditions)) {
				$i = 1;
				do {
					$conditions[$this->alias . '.' . $slug_field] = $this->data[$this->alias][$slug_field] . '-' . $i++;
				} while ($this->hasAny($conditions));
				
				$this->data[$this->alias][$slug_field] .= $conditions[$this->alias . '.' . $slug_field];
			}
		}
		return parent::beforeSave();
	}
/**
 * findByShortName method
 *
 * @param string $slug Area's slug
 * @access public
 * @return boolean
 */
	function findByShortName($slug) {
		if ($areas = Configure::read('Lil.noAreas')) {
			foreach ($areas as $area) {
				if ($area[$this->alias][Configure::read('Lil.areaSlugField')] == $slug) {
					return $area;
				}
			}
			return false;
		} else {
			return $this->find('first', array(
				'conditions' => array(
					$this->alias . '.' . Configure::read('Lil.areaSlugField') => $slug
				),
				'recursive' => -1
			));
		}
	}
/**
 * findByShortId method
 *
 * @param string $id Area's id
 * @access public
 * @return boolean
 */
	function findById($id) {
		if ($areas = Configure::read('Lil.noAreas')) {
			foreach ($areas as $area) {
				if ($area[$this->alias]['id'] == $id) {
					return $area;
				}
			}
			return false;
		} else {
			return $this->find('first', array(
				'conditions' => array(
					$this->alias . '.id' => $id
				),
				'recursive' => -1
			));
		}
	}
/**
 * findForUser method
 *
 * @param mixed $user_id
 * @access public
 * @return boolean
 */
	function findForUser($user_id = null, $type = 'all', $params = array()) {
		$ret = array();
		if (!empty($user_id) || ($user_id = $this->user('id'))) {
			$default = array('conditions' => array());
			if (!$this->isAdmin($user_id)) {
				$AreasUser =& ClassRegistry::init('Lil.AreasUser');
				
				$assoc = Configure::read('Lil.userAssociation');
				$default['conditions'] = array(
					$this->alias . '.id' => $AreasUser->find('list', array(
						'conditions' => array($assoc['foreignKey'] => $user_id), 
						'fields'     => array('id', $assoc['associationForeignKey'])
					))
				); 
			}
			
			$params = $this->callPluginHandlers('before_area_find_for_user', array(
				'user_id' => $user_id,
				'type'    => $type,
				'params'  => array_merge($params, $default)
			));
			return $this->find($type, $params['params']);
			
		}
		return $ret;
	}
}